from contextlib import asynccontextmanager
from typing import Optional

from .base import BaseDatabaseManger, SemaphoreConnectionPool

from ..common import DatabaseConfig, PostgresConfigurationSettings, get_logger

logger = get_logger(__name__)

class VectorDatabaseManager(BaseDatabaseManger):
    def __init__(self, db_config: DatabaseConfig):
        self.pool: Optional[SemaphoreConnectionPool] = None
        super().__init__(db_config)
        """初始化数据库连接池"""
        # 使用默认配置设置
        config_settings=db_config.config_settings
        if config_settings is None:
            config_settings = PostgresConfigurationSettings()
        self.config_settings=config_settings

    def _get_connection_string(self)->str:
        # 验证必要的连接参数
        if not self.user or not self.password:
            error_msg = "非法的数据库连接URL: 用户名或密码为空"
            logger.error(error_msg)
            raise ValueError(error_msg)
        connection_string = f"{self.driver}://{self.user}:{self.password}@{self.host}:{self.port}/{self.db_name}"
        logger.debug(f"数据库连接URL: {self.driver}://{self.user}:********@{self.host}:{self.port}/{self.db_name}")
        return connection_string
    async def initialize(self):
        connection_string=self._get_connection_string()
        # 创建连接池
        connection_pool = SemaphoreConnectionPool(connection_string, self.config_settings)
        await connection_pool.initialize()
        self.pool=connection_pool
    
    @asynccontextmanager
    async def get_connection(self):
        """获取数据库连接"""
        async with self.pool.get_connection() as conn:
            yield conn
    
    async def close(self):
        """关闭连接池"""
        if self.pool:
            await self.pool.close()
            logger.info("数据库连接池已关闭") 
    